import React, { useState, useEffect, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import LanguageSwitcher from './LanguageSwitcher';
import { useAppContext } from '../context/AppContext';

// 菜单项类型定义
export interface MenuItem {
  key: string;
  path: string;
  label: string;
  icon?: React.ReactNode;
  protected?: boolean;
}

// Header组件属性
interface HeaderProps {
  projectName: string;
  menuItems: MenuItem[];
}

const Header: React.FC<HeaderProps> = ({ projectName, menuItems }) => {
  const { userState, logout } = useAppContext();
  const { isLogin, user } = userState;
  const { t } = useTranslation();
  const location = useLocation();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // 过滤当前用户可访问的菜单项
  const accessibleMenuItems = menuItems.filter(item => {
    // 受保护的菜单项只有登录后才能访问
    if (item.protected && !isLogin) {
      return false;
    }
    return true;
  });

  // 处理退出登录
  const handleLogout = () => {
    logout();
    setDropdownOpen(false);
  };

  // 切换下拉菜单
  const toggleDropdown = () => {
    setDropdownOpen(!dropdownOpen);
  };

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <header className="layout-header">
      <div className="header-left">
        <h1 className="project-name">{t(projectName)}</h1>
      </div>
      
      <div className="header-center">
        <nav className="main-nav">
          <ul className="nav-menu">
            {accessibleMenuItems.map(item => (
              <li 
                key={item.key} 
                className={`nav-item ${location.pathname === item.path ? 'active' : ''}`}
              >
                <Link to={item.path} className="nav-link">
                  {item.icon && <span className="nav-icon">{item.icon}</span>}
                  <span className="nav-label">{t(item.label)}</span>
                </Link>
              </li>
            ))}
          </ul>
        </nav>
      </div>
      
      <div className="header-right">
        <div className="header-actions">
          {/* 语言选择器 */}
          <div className="language-switcher">
            <LanguageSwitcher />
          </div>
          
          {/* 用户状态 */}
          <div className="user-status">
            {isLogin ? (
              <div className="user-info" ref={dropdownRef}>
                <button 
                  className={`user-dropdown-trigger ${dropdownOpen ? 'active' : ''}`}
                  onClick={toggleDropdown}
                >
                  <span className="user-greeting">
                    {t('welcome')}，{user?.name || '用户'}
                  </span>
                  <span className={`dropdown-arrow ${dropdownOpen ? 'open' : ''}`}>▼</span>
                </button>
                {dropdownOpen && (
                  <div className="user-dropdown-menu">
                    <div className="dropdown-item">
                      <span className="dropdown-label">{t('user.profile')}</span>
                    </div>
                    <div className="dropdown-item">
                      <span className="dropdown-label">{t('user.settings')}</span>
                    </div>
                    <div className="dropdown-divider"></div>
                    <div className="dropdown-item">
                      <button 
                        className="dropdown-button logout-btn"
                        onClick={handleLogout}
                      >
                        {t('navigation.logout')}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <Link to="/login" className="login-link">
                {t('navigation.login')}
              </Link>
            )}
          </div>
        </div>
      </div>
    </header>
  );
};

export default Header;